package com.zcn.io.web.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zcn.io.common.exception.ServiceException;
import com.zcn.io.web.api.dto.LoginFormDto;
import com.zcn.io.web.api.vo.LoginResultVo;
import com.zcn.io.web.auth.utils.AuthConstants;
import com.zcn.io.web.auth.utils.JwtUtils;
import com.zcn.io.web.auth.LoginUser;
import com.zcn.io.web.service.CacheService;
import com.zcn.io.web.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import com.zcn.io.common.pojo.CommonResult;

/**
 * @desc:
 * @author: 202438 邱建伟
 * @date: 2024/9/16 19:50
 * @Copyright (c) 2024, 江苏金恒信息科技股份有限公司
 */
@RestController
@AllArgsConstructor
@RequestMapping("/auth")
public class AuthController {


    private final AuthenticationManager authenticationManager;
    private final CacheService cacheService;
    private final UserService userService;

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginFormDto loginForm) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginForm.getAccountNo(), loginForm.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (authenticate == null) {
            throw new ServiceException(401, "用户名/密码错误");
        }

        //生成jwtToken
        String jwt = JwtUtils.createJWT(loginForm.getAccountNo());
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        //存到内存中
        cacheService.putInCache(AuthConstants.USER_LOGIN_CACHE_PREFIX + loginForm.getAccountNo(), principal);
        //返回登录成功信息
        LoginResultVo loginResultVo = BeanUtil.copyProperties(principal.getUser(), LoginResultVo.class);
        loginResultVo.setAccessToken(jwt);
        return CommonResult.success(loginResultVo);
    }

}
